package com.yanyi.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.yanyi.music.domain.Song;
import com.yanyi.music.service.impl.SongServiceImpl;
import com.yanyi.music.utils.Consts;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 歌曲控制类
 */
@Api(tags = "歌手API")
@RestController
@RequestMapping("/song")
public class SongController {
    @Autowired
    private SongServiceImpl songService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object addSong(@RequestParam("file") MultipartFile mpFile, HttpServletRequest request) {
        JSONObject object = new JSONObject();
        String singerId = request.getParameter("singerId");
        String name = request.getParameter("name");
        String introduction = request.getParameter("introduction");
        String pic = "/img/songPic/tubiao.jpg";
        String lyric = request.getParameter("lyric");
        if (mpFile.isEmpty()) {
            object.put(Consts.CODE, 0);
            object.put(Consts.MSG, "歌曲上传失败");
            return object;
        }
        String fileName =
                System.currentTimeMillis() + mpFile.getOriginalFilename().substring(mpFile.getOriginalFilename().indexOf("."));
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeUrlPath = "/song/" + fileName;
        try {
            mpFile.transferTo(dest);
            Song song = new Song();
            song.setSingerId(Integer.parseInt(singerId));
            song.setName(name);
            song.setIntroduction(introduction);
            song.setCreateTime(new Date());
            song.setUpdateTime(song.getCreateTime());
            song.setPic(pic);
            song.setUrl(storeUrlPath);
            song.setLyric(lyric);
            int i = songService.insert(song);
            if (i == 1) {
                object.put(Consts.CODE, 1);
                object.put(Consts.MSG, "保存成功");
                object.put("avator", storeUrlPath);
            } else {
                object.put(Consts.CODE, 0);
                object.put(Consts.MSG, "保存失败");
            }
            return object;
        } catch (IOException ioException) {
            object.put(Consts.CODE, 0);
            object.put(Consts.MSG, "保存失败" + ioException.getMessage());
        } finally {
            return object;
        }
    }

    /**
     * 根据歌手Id查询歌曲
     */
    @RequestMapping(value = "/singer/detail", method = RequestMethod.GET)
    public Object songOfSingerId(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("singerId", request.getParameter("singerId"));
        return songService.findAll(map);
    }

    /**
     * 修改歌曲
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object updateSong(HttpServletRequest request) {
        JSONObject object = new JSONObject();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String introduction = request.getParameter("introduction");
        String lyric = request.getParameter("lyric");
        Song song = new Song();
        song.setId(Integer.parseInt(id));
        song.setName(name);
        song.setIntroduction(introduction);
        song.setUpdateTime(new Date());
        song.setLyric(lyric);
        int i = songService.updateByPrimaryKeySelective(song);
        if (i == 1) {
            object.put(Consts.CODE, 1);
            object.put(Consts.MSG, "修改成功");
        } else {
            object.put(Consts.CODE, 0);
            object.put(Consts.MSG, "保存失败");
        }
        return object;
    }

    @RequestMapping(value = "/allSong", method = RequestMethod.GET)
    public Object findAll(HttpServletRequest request) {
        String id = request.getParameter("id");
        String songName = request.getParameter("songName");
        String singerId = request.getParameter("singerId");
        Map<String, Object> map = new HashMap<>();
        map.put("id",id);
        map.put("songName",songName);
        map.put("singerId",singerId);
        List<Song> list = songService.findAll(map);
        return list;
    }
    /**
     * 根据歌曲id查询
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public Object detail(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", request.getParameter("songId"));
        return songService.findAll(map);
    }
    /**
     * 根据歌曲名精确查询歌曲
     */
    @RequestMapping(value = "/songOfSongName", method = RequestMethod.GET)
    public Object songOfSongName(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", request.getParameter("songName"));
        return songService.findAll(map);
    }
    /**
     * 根据歌手名字模糊查询歌曲
     */
    @RequestMapping(value = "/likeSongOfName", method = RequestMethod.GET)
    public Object likeSongOfName(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("songName", request.getParameter("songName"));
        return songService.findAll(map);
    }
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Object delSong(HttpServletRequest request) {
//TODO 未进行物理删除
        return songService.deleteByPrimaryKey(Integer.valueOf(request.getParameter("id")));
    }
    /**
     * 更新歌曲图片
     */
    @RequestMapping(value = "/updateSongPic",method = RequestMethod.POST)
    public Object updateSongPic(@RequestParam("file") MultipartFile avatarFile, @RequestParam("id")int id){
        JSONObject jsonObject = new JSONObject();
        if(avatarFile.isEmpty()){
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"文件上传失败");
            return jsonObject;
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatarFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"img"
                +System.getProperty("file.separator")+"songPic";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/img/songPic/"+fileName;
        try {
            avatarFile.transferTo(dest);
            Song song = new Song();
            song.setId(id);
            song.setPic(storeAvatorPath);
            int flag = songService.updateByPrimaryKeySelective(song);
            if(flag==1){
                jsonObject.put(Consts.CODE,1);
                jsonObject.put(Consts.MSG,"上传成功");
                jsonObject.put("pic",storeAvatorPath);
                return jsonObject;
            }
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"上传失败");
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"上传失败"+e.getMessage());
        }finally {
            return jsonObject;
        }
    }


    /**
     * 更新歌曲
     */
    @RequestMapping(value = "/updateSongUrl",method = RequestMethod.POST)
    public Object updateSongUrl(@RequestParam("file") MultipartFile avatarFile, @RequestParam("id")int id){
        JSONObject jsonObject = new JSONObject();
        if(avatarFile.isEmpty()){
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"文件上传失败");
            return jsonObject;
        }
        //文件名=当前时间到毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatarFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"song";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/song/"+fileName;
        try {
            avatarFile.transferTo(dest);
            Song song = new Song();
            song.setId(id);
            song.setUrl(storeAvatorPath);
            int flag = songService.updateByPrimaryKeySelective(song);
            if(flag==1){
                jsonObject.put(Consts.CODE,1);
                jsonObject.put(Consts.MSG,"上传成功");
                jsonObject.put("avator",storeAvatorPath);
                return jsonObject;
            }
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"上传失败");
            return jsonObject;
        } catch (IOException e) {
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"上传失败"+e.getMessage());
        }finally {
            return jsonObject;
        }
    }
}
